<?php

namespace App\Http\Controllers\Api;

use App\Models\Activity;
use App\Models\Enum\OrderStatusEnum;
use App\Models\Order;
use App\Models\OrderRefund;
use App\Models\OrderUser;
use App\Models\SmsLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;


class UserController extends Controller
{

    public function getInfoFromOpenid(Request $request){
        $openid = $request->openid;

        if (!$openid) {
            return $this->failed('请传openid');
        }
        $user =  DB::table('users')->where('openid',$openid)->first();

        if (!$user) {
            return $this->failed('用户不存在');
        }

        //直接登录
        $token=Auth::guard('api')->attempt(['openid'=>$user->openid,'password'=>$user->openid]);

        $user->token = 'bearer '.$token;
        if($token) {
            return $this->setStatusCode(200)->success($user);
        }



    }

    //获取手机号码 解密
    public function getPhone(Request $request){
        $encryptedData = $request->encryptedData;
        $iv = $request->iv;
        $sessionKey = $request->sessionKey;
        $openid = $request->openid;

//        $encryptedData = "dD4IPMYJhXHYh+Eq+ZEc3DV/5w8mupFm+EbmVY0tL58yKBDNVEOyyCtLrYXQ0xsCy0RQd3DC1DDu2gyZWZDDqFJUphtCBMWHdYyFwNp4iaWcR16qk7mw8Jux55I7YvH2po/B0UYMOZbOyMMeb8tPJJcvuz9lj8e0vw9uoyPuOw5J1S2hKYj0hi9qta38u3YsZo8VTdOE+FRvTbOPm+TjmQ==";
//        $iv = "b1A3pMsv+sxJA/RCFBo24w==";
//        $sessionKey = "jiOLENNRRba9D3UWPmRpPg==";

        if (!$encryptedData || !$iv || !$sessionKey) {
            return $this->failed('参数不全');
        }

        $wechat = new WechatminiController();
        $res = $wechat->encryptor($sessionKey,$iv,$encryptedData);
//        array(4) {
//            ["phoneNumber"] => string(11) "18668234147"
//            ["purePhoneNumber"] => string(11) "18668234147"
//            ["countryCode"] => string(2) "86"
//            ["watermark"] => array(2) {
//                ["timestamp"] => int(1622023488)
//                ["appid"] => string(18) "wxa76ad269911a4108"
//  }
//}
        if($res && $res['phoneNumber']){

            Db::table('users')->where('openid',$openid)->update(['mobile'=>$res['phoneNumber']]);

            $user = Db::table('users')->where('openid',$openid)->first();
            return $this->success($user);


        }else{
            return $this->failed('手机号码获取失败');
        }


        //phoneNumber

    }

    //用户注册
    public function register(Request $request){
        $openid = $request->openid;
        $username = $request->nickname;
        $avatarUrl = $request->avatarUrl;

        if (!$username || !$openid) {
            return $this->failed("参数不全");
        }
        $res =  DB::table('users')->where('openid',$openid)->first();

        if($res){
            $token=Auth::guard('api')->attempt(['openid'=>$openid,'password'=>$openid]);

            $res->token = 'bearer '.$token;
            if($token) {
                return $this->setStatusCode(200)->success($res);
            }
        }


        DB::table('users')->insert(['nickname'=>$username,'openid'=>$openid,'header_img'=>$avatarUrl,'password'=>bcrypt($openid),'created_at'=>date("Y-m-d H:i:s",time())]);
        $res = DB::table('users')->where('openid',$openid)->first();

        $token=Auth::guard('api')->attempt(['openid'=>$openid,'password'=>$openid]);

        $res->token = 'bearer '.$token;
        if($token) {
            return $this->setStatusCode(200)->success($res);
        }

        return $this->failed('登录失败',400);

    }

    public function login1(Request $request){


        $token=Auth::guard('api')->attempt(['name'=>$request->name,'password'=>'123456']);

        if($token) {
            return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
        }
        return $this->failed($token,200);
    }



    //用户登录
    public function login(Request $request){

        $code = $request->code;
        if(!$code)
            return $this->failed("请传code值");
        $wechat = new WechatController();

        $user = $wechat->userFromCode($code);
        if(isset($user['openid'])){
            $result = DB::table('users')->where('openid',$user['openid'])->first();

            if(!$result){//用户不存在

                DB::table('users')->insert(['nickname'=>$user['nickname'],'openid'=>$user['openid'],'header_img'=>$user['Avatar'],'password'=>bcrypt($user['openid']),'created_at'=>date("Y-m-d H:i:s",time())]);

                $result = DB::table('users')->where('openid',$user['openid'])->first();
            }
        }else{
            return $this->failed("获取失败");
        }

        $token=Auth::guard('api')->attempt(['openid'=>$user['openid'],'password'=>$user['openid']]);

        $result->token = 'bearer '.$token;
        if($token) {
            return $this->setStatusCode(200)->success($result);
        }
        return $this->failed('登录失败',400);
    }



//用户退出
    public function logout(){
        Auth::guard('api')->logout();
        return $this->success('退出成功...');
    }

    //获取个人信息
    public function getUserInfo(){

        $user = Auth::guard('api')->user();

        return $this->success($user);

    }



    //用户生成订单
    public function addOrder(Request $request){

        $activity_id = $request->activity_id;
        $person = $request->person;
        $activity =  DB::table('activity')->find($activity_id);
        $count = OrderUser::where('activity_id',$activity_id)->where('pay_status',1)->where('status','<',2)->count();
        if(!$activity)
            return $this->failed("活动不存在");

        if($activity->price<=0){
            return $this->failed("订单金额有误");
        }
        if($activity->join_time < date("Y-m-d H:i:s"))
            return $this->failed("不在报名时间内");

        if($activity->status == 2)
            return $this->failed("活动已结束");

        if($count+$person > $activity->person){
            return $this->failed("报名人数超出");
        }


        $user = Auth::guard('api')->user();

//        $is_order = DB::table('order')->where(['activity_id'=>$activity_id,'user_id'=>$user['id']])->first();
//        if($is_order && $is_order->pay_status == 1 && $is_order->order_status<2){
//            return $this->failed("已报名相同活动");
//        }

        $order = new Order();

        DB::beginTransaction();
        $order->user_id = $user['id'];
        $order->order_sn = $this->getOrderSn();
        $order->activity_id = $activity_id;
        $order->money = $activity->price * $request->person;
        $order->person =  $request->person;
        $order->province =  $request->province;

        $order->city =  $request->city;
        $order->district =  $request->district;
       if($activity->check_rule==1)
           $order->check_status = 1; //订单状态待审核
        $res1 = $order->save();

        //保存购票人信息

        $data = [];

        foreach ($request->process as $k=>$v){
            $data[$k]['order_id'] = $order->id;
            $data[$k]['activity_id'] = $activity_id;
            $data[$k]['price'] = $activity->price;
            $data[$k]['name'] = $v['name'];
            $data[$k]['mobile'] = $v['mobile'];
            $data[$k]['values'] = $v['values'];
            $data[$k]['created_at'] = date("Y-m-d H:i:s");
        }

       $res2 = OrderUser::insert($data);

        if($res1 && $res2){
            DB::commit();

            $pay = new WechatPayController();
            return $pay->prepayOrder($order->id,$user['openid']);

        }else{
            DB::rollBack();
            return $this->failed("订单生成失败");
        }

    }

    //去支付
    public function payOrder(Request $request)
    {
        $order_id = $request->order_id;
        $user = Auth::guard('api')->user();

        $order = DB::table('order')->where('user_id',$user['id'])->find($order_id);

        $activity = DB::table('activity')->find($order->activity_id);

        $count = Order::where('activity_id',$order->activity_id)->where('pay_status',1)->sum('person');
        if(!$activity)
            return $this->failed("活动不存在");


        if($activity->status == 2)
            return $this->failed("活动已结束");

        if($count+$order->person > $activity->person){
            return $this->failed("报名人数超出");
        }

        if(!$order)
            return $this->failed('订单有误');

        $pay = new WechatPayController();

        return $this->success($pay->prepayOrder($order->id,$user['openid']));
    }

    //用户取消订单
    public function cancelOrder(Request $request){

        $order_id = $request->order_id;
        $user = Auth::guard('api')->user();
        $order = Order::with('activity')->where('user_id',$user['id'])->find($order_id);
        $activity = Activity::find($order->activity_id);

        if(!$order)
            return $this->failed('订单不存在');

        if($order->pay_status==0){
            $order->order_status = 5;
            $order->save();
            return $this->success("已取消");
        }

        if($order->pay_status==1){
            if($order->order_status>1)
                return $this->failed("当前状态不可取消");

            if($activity->cancel_rule=="不可取消")
                return $this->failed('活动不可取消');

            if($activity->start_time < date("Y-m-d H:i:s"))
                return $this->failed("活动开始后不可取消");

            return $this->refundOrder($order_id);
        }


    }

    //用户申请退款
    public function refundOrder($order_id)
    {


        DB::beginTransaction();
        $order = Order::with('order_user')->find($order_id);

        $wechat = new WechatPayController();
        if($order->order_status== OrderStatusEnum::UNCHECK){ //退全部
            $refund_money = $order['money'];
            $order->order_status = OrderStatusEnum::REFUND;
        }
        if($order->order_status==OrderStatusEnum::CHECKED){ //退部分
            $refund_money = 0;
            foreach ($order->order_user as $k=>$v){
                if($v['status'] == 0){
                    $refund_money+= $v['price'];
                }
            }

            $order->order_status = OrderStatusEnum::SOME_REFUND;
        }
        $result = $wechat->refund($order,$refund_money);
        $order_refund = new OrderRefund();
        $order_refund->order_id = $order_id;
        $order_refund->user_id = $order->user_id;
        $order_refund->activity_id = $order['activity_id'];
        $order_refund->money = $refund_money;

        if($result['return_code']=== 'FAIL')
            return $this->failed("退款失败");
        if($result['result_code'] ==='SUCCESS'){

            $order_refund->refund_sn = $result['out_refund_no'];
            $order_refund->status = 'SUCCESS';
            $res1 = $order->save(); //修改订单状态

            $res2 = OrderUser::where('order_id',$order_id)->where('status',0)->update(['status'=>2]); //修改order_user状态
        }
        if($result['result_code'] ==='FAIL'){
            $res1 = $res2 = true;
            $order_refund->msg = $result['err_code_des'];
            $order_refund->status = 'FAIL';
        }
        $res3 = $order_refund->save(); //保存退款信息

        if($res1&&$res2&&$res3){
            DB::commit();
            return $this->success("操作成功");
        }else{
            DB::rollBack();
            return $this->failed("操作失败");
        }


    }


    public function getOrderSn(){

        $rand = mt_rand(10000, 99999);

        return date('YmdHis', time()) . $rand;

    }

    //用户获取订单列表
    public function getUserOrderList(Request $request){

        $user = Auth::guard('api')->user();

        $title = $request->title;
        $status = $request->status;
        //全部 0  待支付1  报名成功2  已取消3

        $where = function($query) use ($status){
            if($status==1){//待支付
                $query->where('pay_status',0);
            }
            if($status==2){//报名成功
                $query->where('pay_status',1)->where('order_status','<',4);
            }
            if($status==3){//已取消
                $query->where('order_status',5);
            }
            if($status==4){//已退款
                $query->whereIn('order_status',[3,4]);
            }

            if($status==5){//待核销
                $query->where('pay_status',1)->where('order_status','<',2);
            }

        };

        $order = Order::with('activity:id,title')
            ->where('user_id',$user['id'])->where($where)
            ->when($title,function($query) use ($title){
                $query->where(function ($query) use ($title){
                    return $query->whereHas('activity', function ($query) use ($title) {
                        return $query->where('title', 'like', '%'.$title.'%');
                    });
                });

            })->orderBy('created_at','desc')->paginate($request->pageSize?:15);

        return $this->success($order);
    }

    //获取订单详情
    public function getUserOrderDetail(Request $request){

        $id = $request->id;

        $order = Order::with(["order_user:id,order_id,name,mobile,status,values","activity:id,title,start_time,keys,address,position"])
           ->select(['id','person','money','activity_id','order_status','pay_status','check_status','created_at'])
            ->find($id);
        foreach ($order->order_user as $k=>$v) {
            $data = $order->id.','.$v['id'].','.time();

            $order['order_user'][$k]['data'] = base64_encode($data);

        }

        return $this->success($order);
    }





    //发送手机验证码
    public function sendCode(Request $request){
        $mobile = $request->mobile;
        $user1 = Auth::guard('api')->user();
        if(!$mobile)
            return $this->failed('请传手机号');

        $user = User::where('mobile',$mobile)->first();

        if($user && $user['id'] != $user1['id'])
            return $this->failed('该手机号已存在');

        $sms = new SmsLog();

        $res =$sms->sendVerifyCode($mobile);

        if($res){
            return $this->success('发送成功');

        }
        return $this->failed('发送失败');

    }


    //手机验证码验证
    public function checkCode(Request $request){

        $mobile = $request->mobile;
        $name = $request->name;
        $code = $request->code;

        if(!$mobile)
            return $this->failed('请填写手机号');

        if(!$code)
            return $this->failed('请填写验证码');

        $sms = new SmsLog();
        $res = $sms->checkCode($mobile,$code);

        if($res===true){
            $user=Auth::guard('api')->user();
            $user['mobile'] = $mobile;
            $user['name'] = $name;
            $user->save();
            return $this->success($user);
        }else{
            return $this->failed($res);
        }


    }



    public function getMyQrList(){

        $user = Auth::guard('api')->user();
        $order_list = Order::with(["order_user:id,order_id,name,mobile,status","activity:id,title,start_time"])
            ->where('user_id',$user['id'])->select(['id','person','money','activity_id','order_status','created_at'])
            ->get();

        foreach ($order_list as $k => $v){

            foreach ($v->order_user as $kk=>$vv) {
                $data = $v->id.','.$vv['id'].','.time();

                $order_list[$k]['order_user'][$kk]['data'] = base64_encode($data);

            }

        }

        return $this->success($order_list);


    }

    //轮询获取二维码核销状态
    public function getCheckStatus(Request $request){

        $id = $request->id;

        $info = OrderUser::select(['id','status'])->find($id);


        return $this->success($info);
    }

    //二维码刷新
    public function QrCodeRefresh(Request $request){

        $id = $request->id;

        $info = OrderUser::find($id);

        if(!$info)
            return $this->failed('参数有误');

        $data = $info->order_id.','.$info->id.','.time();

        $data = base64_encode($data);

        return $this->success($data);
    }

}
